const Base64 = require("js-base64").Base64

// 记住账号密码中的常量key,避免和其他系统混淆
let rememberAccountKey='OSSWebAccount';
let rememberPwdKey='OSSWebPwd';

// 判断是否重复请求的间隔时间(单位毫秒)
let intervalTime = 1500

// token的key值
const token = "OSSWebToken";
const userInfoKey = "OSSWebUserInfo";
const loginFlagKey = "OSSWebLoginFlag";
export function setToken(val){
  localStorage.setItem(token,val)
}
export function getToken() {
  return localStorage.getItem(token);
}
export function setLoginFlag(val){
  localStorage.setItem(loginFlagKey,val+"")
}
export function getLoginFlag() {
  return localStorage.getItem(loginFlagKey)+"";
}
export function setUserInfo(val){
  let userInfoString = ""
  if (val) {
    userInfoString = JSON.stringify(val)
  }
  localStorage.setItem(userInfoKey,userInfoString)
}
export function getUserInfo() {
  let userInfo = ""
  if (localStorage.getItem(userInfoKey)) {
    userInfo = JSON.parse(localStorage.getItem(userInfoKey))
  }
  return userInfo;
}
export function removeToken(val) {
  localStorage.removeItem(token);
}
// 记住账号密码
export function rememberPwd(userAccount,userPwd) {
  localStorage.setItem(rememberAccountKey,userAccount)
  // 密码加密
  let encodePwd = Base64.encode(userPwd)
  localStorage.setItem(rememberPwdKey,encodePwd)
}
// 获取记住的账号密码信息
export function getRememberPwdInfo() {
  let userAccount = localStorage.getItem(rememberAccountKey)
  let userPwd = localStorage.getItem(rememberPwdKey)
  // 密码解密
  if (userPwd) {
    userPwd = Base64.decode(userPwd)
  }
  return {
    userAccount,
    userPwd
  }
}
// 删除记住的账号密码
export function removeRememberPwdInfo() {
  localStorage.removeItem(rememberAccountKey);
  localStorage.removeItem(rememberPwdKey);
}
// 记录请求参数和地址
export function rememberRequestAndParam(url,params) {
  if (Object.keys(params).length != 0) {
    params = {...params,time:new Date().getTime()}
  } else {
    params = {time:new Date().getTime()}
  }
  localStorage.setItem(url.trim(),JSON.stringify(params))
  // 定时删除
  window.setTimeout(()=>{
    localStorage.removeItem(url.trim())
  },intervalTime)
}
// 判断是否重复请求
export function isRepetRequest(url,params2) {
  let params = localStorage.getItem(url.trim())
  if (!params) {
    return false
  }
  params = JSON.parse(params)
  let time = params.time
  delete params.time
  let paramsStr1 = JSON.stringify(params)
  let paramsStr2 = JSON.stringify(params2)
  console.log('两次请求入参',paramsStr1, paramsStr2)
  // 请求参数相同
  if (paramsStr1 == paramsStr2) {
    let currentTime = new Date().getTime()
    // 两次相同的请求间隔不能小于1秒, 否则视为相同的请求
    if ((currentTime - time) < intervalTime) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }

}
// 设置最后一次打开的tab信息
export function setLastTabInfo(tabInfo){
  localStorage.setItem('lastTabInfo',JSON.stringify(tabInfo))
}
//获取最后一次打开的tab信息
export function getLastTabInfo(){
  return JSON.parse(localStorage.getItem('lastTabInfo'))
}

